# src/utils/minio_client.py

import boto3
from botocore.exceptions import ClientError
from src.config import (
    MINIO_ENDPOINT,
    MINIO_ACCESS_KEY,
    MINIO_SECRET_KEY,
    REGION_NAME,
    MINIO_BUCKET_NAME,
)

# 单例 s3 客户端
s3_client = boto3.client(
    "s3",
    endpoint_url=MINIO_ENDPOINT,
    aws_access_key_id=MINIO_ACCESS_KEY,
    aws_secret_access_key=MINIO_SECRET_KEY,
    region_name=REGION_NAME,
)

def ensure_bucket(bucket_name=MINIO_BUCKET_NAME):
    try:
        s3_client.head_bucket(Bucket=bucket_name)
    except ClientError as e:
        error_code = int(e.response['Error']['Code'])
        if error_code == 404:
            s3_client.create_bucket(Bucket=bucket_name)
        else:
            raise

__all__ = ["s3_client", "ensure_bucket"]
